package com.it.reggie.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.it.reggie.common.R;
import com.it.reggie.dto.DishDto;
import com.it.reggie.entity.Category;
import com.it.reggie.entity.Dish;
import com.it.reggie.entity.DishFlavor;
import com.it.reggie.service.CategoryService;
import com.it.reggie.service.DishFlavorService;
import com.it.reggie.service.DishService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;


/**
 * 菜品管理
 * 菜品和菜品口味的相关操作
 */
@RestController
@RequestMapping("/dish")
@Slf4j
public class DishController {
    @Autowired
    private DishService dishService;

    @Autowired
    private DishFlavorService dishFlavorService;

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 根据id查询菜品信息和对应的口味信息
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public R<DishDto> get(@PathVariable Long id){
        DishDto dishDto = dishService.getByIdWithFlavor(id);
        return R.success(dishDto);
    }

    /**
     * 新增菜品
     * @param dishDto
     * @return
     */
    @PostMapping
    public R<String> save(@RequestBody DishDto dishDto){
        log.info(dishDto.toString());
        dishService.saveWithFlavor(dishDto);

        //清理所有菜品的缓存数据,即获取所有以dish_xxx开头的key
        /*Set keys = redisTemplate.keys("dish_*");
        redisTemplate.delete(keys);*/

        //清理某个分类下面的菜品缓存数据
        String key = "dish_" + dishDto.getCategoryId() + "_1";
        redisTemplate.delete(key);
        return R.success("新增菜品成功");
    }

    @GetMapping("/page")
    public R<Page> page(int page, int pageSize,String name){
        //分页构造器
        Page<Dish> pageInfo = new Page<>(page,pageSize);

        //条件构造器
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        //过滤
        queryWrapper.eq(StringUtils.isNotEmpty(name),Dish::getName,name);
        //排序
        queryWrapper.orderByDesc(Dish::getUpdateTime);
        //执行
        dishService.page(pageInfo,queryWrapper);
        //新的条件构造器
        Page<DishDto> dishDtoPage = new Page<>();
        //对象拷贝
        BeanUtils.copyProperties(pageInfo,dishDtoPage,"records");

        List<Dish> records = pageInfo.getRecords();

        List<DishDto> list = records.stream().map((item) -> {

            DishDto dishDto = new DishDto();
            //拷贝菜品信息
            BeanUtils.copyProperties(item, dishDto);

            //获取分类ID
            Long categoryId = item.getCategoryId();
            //获取分类对象
            Category category = categoryService.getById(categoryId);
            if (category != null) {
                //获取分类名称
                String categoryName = category.getName();
                //设置分类名称
                dishDto.setCategoryName(categoryName);
            }
            return dishDto;
        }).collect(Collectors.toList());
        dishDtoPage.setRecords(list);
        return  R.success(dishDtoPage);
    }
    /**
     * 菜品信息分页查询
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
   /* @GetMapping("/page")
    public R<Page> page (int page,int pageSize,String name){
        // 构造分页构造器对象
        Page<Dish> pageInfo = new Page<>(page, pageSize);
        //条件构造器
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        // 添加过滤条件,根据搜索name模糊查询
        //select * from dish where name = ? ;
        queryWrapper.like(name != null,Dish::getName,name);
        // 添加排序条件
        //select * from dish order by math desc ;
        queryWrapper.orderByDesc(Dish::getUpdateTime);
        // 执行分页条件查询
        dishService.page(pageInfo,queryWrapper);

        //1.构造新的名为dishDtoPage分页器对象,泛型为DishDto
        Page<DishDto> dishDtoPage = new Page<>();
        //2.构造器对象拷贝工具BeanUtils:Dish的构造器对象pageInfo拷贝到DishDto的dishDtoPage对象
            //2.1排除Page的records属性,即所有的分页数据
        BeanUtils.copyProperties(pageInfo,dishDtoPage,"records");
        //3.获取菜品查询页面数据集合
        List<Dish> records = pageInfo.getRecords();
        //4.用Stream流处理菜品集合,将dish对象所有属性及categoryName封装给dishDto对象 并映射返回dishDto对象给list集合
        List<DishDto> list = records.stream().map((item) -> {

            DishDto dishDto = new DishDto();
            //4.4拷贝菜品信息的其他属性(即父类的dish属性)给dishDto对象
            BeanUtils.copyProperties(item, dishDto);

            //4.1从每条菜品信息中获取分类id
            Long categoryId = item.getCategoryId();
            //4.2注入categoryService,根据categoryId获取category对象
            Category category = categoryService.getById(categoryId);
            //4.3判断分类对象是否为空
            if (category != null) {
                //4.3.1从category中得到分类名称name属性,
                String categoryName = category.getName();
                //4.3.2创建dishDto对象,并给dishDto对象的categoryName属性设置name的属性值
                dishDto.setCategoryName(categoryName);
            }
            return dishDto;
        }).collect(Collectors.toList());
        //给分页对象添加所有信息即完整的dishDto=(dish表+categoryName属性
        dishDtoPage.setRecords(list);
        return R.success(dishDtoPage);
    }*/



    /**
     * 修改菜品
     * @param dishDto
     * @return
     */
    @PutMapping
    public R<String> update(@RequestBody DishDto dishDto){
        log.info(dishDto.toString());
        dishService.updateWithFlavor(dishDto);

        /*//清理某个分类下面的菜品缓存数据
        String key = "dish_" + dishDto.getCategoryId() + "_1";
        redisTemplate.delete(key);*/

        //清理所有菜品的缓存数据
        Set keys = redisTemplate.keys("dish_*"); //获取所有以dish_xxx开头的key
        redisTemplate.delete(keys); //删除这些key
        return R.success("修改菜品成功");
    }

    /**
     * 根据菜品分类ID,查询菜品列表
     * @param dish
     * @return
     */
    @GetMapping("/list")
    public R<List<DishDto>> list(Dish dish){
        List<DishDto> dishDtoList = null;
        //动态构造key
        String key = "dish_" + dish.getCategoryId() + "_" + dish.getStatus();
        //先从redis中获取数据
        dishDtoList = (List<DishDto>) redisTemplate.opsForValue().get(key);
        if(dishDtoList != null){
            //如果存在,直接返回,无需查询数据库
            return R.success(dishDtoList);
        }

        //构造查询条件
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(dish.getCategoryId() != null,Dish::getCategoryId,dish.getCategoryId());
        //添加条件，查询状态为1（起售状态）的菜品
        queryWrapper.eq(Dish::getStatus,1);
        //添加排序条件
        queryWrapper.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);

        List<Dish> list = dishService.list(queryWrapper);
        dishDtoList = list.stream().map((item) -> {
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(item, dishDto);
            //分类ID
            Long categoryId = item.getCategoryId();
            //根据ID查询分类对象
            Category category = categoryService.getById(categoryId);
            if (category != null) {
                String categoryName = category.getName();
                dishDto.setCategoryName(categoryName);
            }
            //当前菜品的id
            Long dishId = item.getId();
            LambdaQueryWrapper<DishFlavor> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(DishFlavor::getDishId, dishId);
            List<DishFlavor> dishFlavorList = dishFlavorService.list(lambdaQueryWrapper);
            dishDto.setFlavors(dishFlavorList);
            return dishDto;
        }).collect(Collectors.toList());

        //如果不存在,查询数据库,将查询到的菜品数据缓存到Redis
        redisTemplate.opsForValue().set(key,dishDtoList,60, TimeUnit.MINUTES);
        return R.success(dishDtoList);
    }

}
